import React, { useState, useEffect, useRef } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  Image,
  TouchableOpacity,
  SafeAreaView,
  StatusBar,
  FlatList,
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { useNavigation } from '@react-navigation/native';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import PagerView from 'react-native-pager-view';
import { PixelRatio } from 'react-native';
import { GetData } from '../instance/api';
const pixelRatio = PixelRatio.get();
export default function HomeScreen() {
  const navigation = useNavigation();
  const [activeBanner, setActiveBanner] = useState(0);
  const pagerRef = useRef(null);
  const [data, setData] = useState([]);
  // Banner images
  const bannerImages = [
    require('../src/images/banners/banner1.png'),
    require('../src/images/banners/banner2.png'),
    require('../src/images/banners/banner3.png'),
    require('../src/images/banners/banner4.png'),
    require('../src/images/banners/banner5.png'),
    require('../src/images/banners/banner6.png'),
  ];
  const images = {
    '../assets/1.jpg': require('../assets/1.jpg'),
    '../assets/2.jpg': require('../assets/2.jpg'),
    '../assets/3.jpg': require('../assets/3.jpg'),
    '../assets/4.jpg': require('../assets/4.jpg'),
    '../assets/5.jpg': require('../assets/5.jpg'),
    '../assets/6.jpg': require('../assets/6.jpg'),
    '../assets/7.jpg': require('../assets/7.jpg'),
    '../assets/8.jpg': require('../assets/8.jpg'),
    // 继续添加你的图片
  };

  useEffect(() => {
    GetData().then(res => {
      // console.log('数据数据获取', res);
      setData(res.data.data);
    });
  }, []);

  // Auto slide banner
  useEffect(() => {
    const interval = setInterval(() => {
      if (pagerRef.current) {
        const nextPage = (activeBanner + 1) % bannerImages.length;
        pagerRef.current.setPage(nextPage);
      }
    }, 3000);

    return () => clearInterval(interval);
  }, [activeBanner]);

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar backgroundColor="#ffffff" barStyle="dark-content" />

      {/* Header with Search */}
      <View style={styles.header}>
        <View style={styles.headerLeft}>

          <Image
            source={require('../game/11.png')}
            style={{ width: 100, height: 33 }}
            resizeMode="cover"
          />
          {/* <Text style={{color: '#fff', fontSize: wp(4), fontWeight: 'bold',marginLeft:-5}}>盈通平台</Text> */}
        </View>
        <View style={styles.searchContainer}>
          <Icon name="search" size={20} color="#fff" />
        </View>
      </View>

      <ScrollView showsVerticalScrollIndicator={false}>
        {/* Banner Carousel */}
        <View style={styles.bannerContainer}>
          <PagerView
            ref={pagerRef}
            style={styles.pagerView}
            initialPage={0}
            onPageSelected={(e) => setActiveBanner(e.nativeEvent.position)}
          >
            {bannerImages.map((image, index) => (
              <View key={index} style={styles.bannerSlide}>
                <Image
                  source={image}
                  style={styles.bannerImage}
                  resizeMode="cover"
                />
              </View>
            ))}
          </PagerView>

          {/* Indicators */}
          <View style={styles.indicatorContainer}>
            {bannerImages.map((_, index) => (
              <View
                key={index}
                style={[
                  styles.indicator,
                  index === activeBanner && styles.indicatorActive,
                ]}
              />
            ))}
          </View>
        </View>

        {/* Category Icons */}
        <View style={styles.categoryContainer}>
          <TouchableOpacity style={styles.categoryItem} onPress={()=>navigation.navigate('PaymentScreen')}>
            <View style={[styles.categoryIcon, { backgroundColor: '#FFA500' }]}>
              <Image source={require('../game/12.png')} style={{ width: 20, height: 20 }} />
            </View>
            <Text style={styles.categoryText}>充值中心</Text>
          </TouchableOpacity>

          <TouchableOpacity style={styles.categoryItem}>
            <View style={[styles.categoryIcon, { backgroundColor: '#FFD700' }]}>
              <Image source={require('../game/13.png')} style={{ width: 20, height: 20 }} />
            </View>
            <Text style={styles.categoryText}>余额充值</Text>
          </TouchableOpacity>

          <TouchableOpacity style={styles.categoryItem}>
            <View style={[styles.categoryIcon, { backgroundColor: '#4B9EE8' }]}>
              <Image source={require('../game/14.png')} style={{ width: 20, height: 20 }} />
            </View>
            <Text style={styles.categoryText}>手游专区</Text>
          </TouchableOpacity>

          <TouchableOpacity style={styles.categoryItem}>
            <View style={[styles.categoryIcon, { backgroundColor: '#FF6B81' }]}>
              <Image source={require('../game/15.png')} style={{ width: 20, height: 20 }} />
            </View>
            <Text style={styles.categoryText}>端游专区</Text>
          </TouchableOpacity>

          <TouchableOpacity style={styles.categoryItem}>
            <View style={[styles.categoryIcon, { backgroundColor: '#1DD1A1' }]}>
              <Image source={require('../game/16.png')} style={{ width: 20, height: 20 }} />
            </View>
            <Text style={styles.categoryText}>我的收藏</Text>
          </TouchableOpacity>
        </View>

        {/* Order Status */}
        <View style={styles.orderStatusContainer}>
          <Text style={styles.orderStatusText}><Text style={{ color: 'black', fontWeight: 'bold' }}>最新成交订单:</Text> 任超凡-账号了 41314541≥24{'>'}创始人<Text style={{ color: '#cf1322' }}> ¥306.01</Text></Text>
        </View>

        {/* Game Categories Header - Hot Mobile Games */}
        <View style={styles.gameSection}>
          <View style={styles.gameHeaderContainer}>
            <Text style={styles.gameHeaderTitle}>热门手游</Text>

            <Text style={styles.gameHeaderTitle1}>热门端游</Text>
          </View>

          <View style={styles.gameGridContainer}>
            {/* Row 1 */}
            <TouchableOpacity style={styles.gameItem}>
              <Image source={require('../src/images/barbar/王者荣耀.png')} style={styles.gameIcon} />
              <Text style={styles.gameTitle}>王者荣耀</Text>
            </TouchableOpacity>

            <TouchableOpacity style={styles.gameItem}>
              <Image source={require('../src/images/barbar/航海王.png')} style={styles.gameIcon} />
              <Text style={styles.gameTitle}>航海王</Text>
            </TouchableOpacity>

            <TouchableOpacity style={styles.gameItem}>
              <Image source={require('../src/images/barbar/神武.png')} style={styles.gameIcon} />
              <Text style={styles.gameTitle}>神将4</Text>
            </TouchableOpacity>

            <TouchableOpacity style={styles.gameItem}>
              <Image source={require('../src/images/barbar/火影.png')} style={styles.gameIcon} />
              <Text style={styles.gameTitle}>火影忍者</Text>
            </TouchableOpacity>

            {/* Row 2 */}
            <TouchableOpacity style={styles.gameItem}>
              <Image source={require('../src/images/barbar/口袋.png')} style={styles.gameIcon} />
              <Text style={styles.gameTitle}>口袋妖怪</Text>
            </TouchableOpacity>

            <TouchableOpacity style={styles.gameItem}>
              <Image source={require('../src/images/barbar/穿越.png')} style={styles.gameIcon} />
              <Text style={styles.gameTitle}>穿越火线</Text>
            </TouchableOpacity>

            <TouchableOpacity style={styles.gameItem}>
              <Image source={require('../src/images/barbar/闪烁.png')} style={styles.gameIcon} />
              <Text style={styles.gameTitle}>闪烁之光</Text>
            </TouchableOpacity>

            <TouchableOpacity style={styles.gameItem}>
              <Image source={require('../src/images/barbar/仙境传说.png')} style={styles.gameIcon} />
              <Text style={styles.gameTitle}>仙侠传说</Text>
            </TouchableOpacity>

            {/* Row 3 */}
            <TouchableOpacity style={styles.gameItem}>
              <Image source={require('../src/images/barbar/率土.png')} style={styles.gameIcon} />
              <Text style={styles.gameTitle}>率土之滨</Text>
            </TouchableOpacity>

            <TouchableOpacity style={styles.gameItem}>
              <Image source={require('../src/images/barbar/少年三国志.png')} style={styles.gameIcon} />
              <Text style={styles.gameTitle}>少年三国志</Text>
            </TouchableOpacity>

            <TouchableOpacity style={styles.gameItem}>
              <Image source={require('../src/images/barbar/三国志.png')} style={styles.gameIcon} />
              <Text style={styles.gameTitle}>三国志</Text>
            </TouchableOpacity>

            <TouchableOpacity style={styles.gameItem}>
              <Image source={require('../src/images/barbar/阿拉德之怒.png')} style={styles.gameIcon} />
              <Text style={styles.gameTitle}>阿拉德之怒</Text>
            </TouchableOpacity>
          </View>

          <Text style={styles.moreText}>查看全部游戏 {'>'}</Text>

        </View>

        <View style={styles.divider} />

        {/* Hot Products */}
        <View style={styles.sectionHeader}>
          <Text style={styles.sectionTitle}>热销商品</Text>
        </View>

        <FlatList
          data={data}
          numColumns={2}
          keyExtractor={(item, index) => index.toString()}
          renderItem={({ item }) => (
            <TouchableOpacity
              style={styles.productItem}
              onPress={() => navigation.navigate('DetailScreen', { item })}
            >
              <Image source={images[item.image]} style={styles.productImage} />
              <Text style={styles.productTitle}>{item.title}</Text>
              <View style={styles.productPriceContainer}>
                <View style={styles.discountLabel}>
                  <Text style={styles.discountText}>降价</Text>
                </View>
                <View style={styles.discountLabel2}>
                  <Text style={styles.discountText2}>-25%</Text>
                </View>
                <Text style={styles.productPrice}>¥ {item.price}</Text>
                <Text style={styles.productSold}>{item.num}人付款</Text>
              </View>
              <Text style={styles.productCategory}>王者荣耀</Text>
            </TouchableOpacity>
          )}
          scrollEnabled={false}
          nestedScrollEnabled={true}
          style={styles.productsContainer}
        />

        <Text style={styles.moreText}>查看全部游戏 {'>'}</Text>

        <View style={styles.footer} />
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    marginTop: "1000px",
    flex: 1,
    backgroundColor: 'white',
  },
  header: {
    backgroundColor: '#cf1322',
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: wp(4),
    paddingVertical: hp(1),
  },

  searchContainer: {
    flex: 1,
    alignItems: 'flex-end',
  },
  bannerContainer: {
    position: 'relative',
    height: hp(25),
  },
  pagerView: {
    height: hp(25),
  },
  bannerSlide: {
    flex: 1,
  },
  bannerImage: {
    width: wp(100),
    height: hp(30),
  },
  indicatorContainer: {
    position: 'absolute',
    bottom: 0,
    flexDirection: 'row',
    justifyContent: 'center',
    width: '100%',
    paddingBottom: 10,
  },
  indicator: {
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: 'rgba(255, 255, 255, 0.6)',
    marginHorizontal: 3,
  },
  indicatorActive: {
    backgroundColor: '#fff',
    width: 16,
  },
  categoryContainer: {
    flexDirection: 'row',
    backgroundColor: '#fff',
    paddingVertical: hp(2),
    justifyContent: 'space-around',
  },
  categoryItem: {
    alignItems: 'center',
    width: wp(18),
  },
  categoryIcon: {
    width: wp(10),
    height: wp(10),
    borderRadius: wp(5),
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 5,
  },
  categoryIconText: {
    color: '#fff',
    fontSize: wp(4),
    fontWeight: 'bold',
  },
  categoryText: {
    fontSize: wp(3),
    color: '#333',
  },
  orderStatusContainer: {
    backgroundColor: '#fff',
    padding: wp(3),
    marginVertical: hp(1),
  },
  orderStatusText: {
    color: '#333',
    fontSize: wp(3),
  },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    padding: wp(3),
    backgroundColor: '#fff',
  },
  sectionTitle: {
    fontSize: wp(4),
    fontWeight: 'bold',
    color: '#333',
  },
  gameGridContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    backgroundColor: '#fff',
    paddingVertical: hp(1),
  },
  gameItem: {
    width: '25%',
    alignItems: 'center',
    marginBottom: hp(2.5),
  },
  gameIcon: {
    width: wp(14),
    height: wp(14),
    borderRadius: wp(2),
    marginBottom: 8,
  },
  gameTitle: {
    fontSize: wp(3),
    color: '#333',
    textAlign: 'center',
  },
  moreText: {
    textAlign: 'center',
    color: '#999',
    fontSize: wp(3),
    padding: wp(3),
    backgroundColor: '#fff',
  },
  divider: {
    height: hp(1),
    backgroundColor: '#f5f5f5',
  },
  productsContainer: {
    backgroundColor: '#fff',
    width: '100%',
  },
  productItem: {
    width: wp(50),
    backgroundColor: '#fff',
    marginBottom: hp(1),
    padding: wp(1),
  },
  productImage: {
    width: '100%',
    height: hp(15),
    borderRadius: wp(-10),
  },
  productTitle: {
    fontSize: wp(3),
    color: '#333',
    marginTop: 5,
    lineHeight: wp(4),
    height: hp(5.5),
  },
  productPriceContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 5,
  },
  discountLabel: {
    backgroundColor: '#E71B24',
    paddingHorizontal: 4,
    paddingVertical: 1,
    borderRadius: 3,
    marginRight: 5,
  },
  discountText: {
    color: '#fff',
    fontSize: wp(2.5),
  },
  discountLabel2: {
    backgroundColor: '#E71B24',
    paddingHorizontal: 4,
    paddingVertical: 1,
    borderRadius: 3,
    marginRight: 5,
  },
  discountText2: {
    color: '#fff',
    fontSize: wp(2.5),
  },
  productPrice: {
    color: '#E71B24',
    fontWeight: 'bold',
    fontSize: wp(3.5),
    marginRight: 5,
  },
  productSold: {
    color: '#999',
    fontSize: wp(2.5),
  },
  productCategory: {
    color: '#666',
    fontSize: wp(3),
    marginTop: 5,
  },
  footer: {
    height: hp(5),
  },
  gameSection: {
    padding: wp(3),
    backgroundColor: '#fff',
  },
  gameHeaderContainer: {
    flexDirection: 'row',

    alignItems: 'center',
  },
  gameHeaderTitle: {
    fontSize: wp(4),
    fontWeight: 'bold',
    color: '#333',
  },
  gameHeaderTitle1: {
    marginLeft: wp(10),
    fontSize: wp(4),

    color: 'grey',
  },
  headerLeft: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    gap: 10
  },
  headerWrap: {
    width: '100%',
    backgroundColor: '#CF1322',
    height: 44, // 导航栏高度
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
    // 你可以去掉 borderRadius 和 paddingTop
  },
});
